using System;
using System.Collections.Generic;
using System.Text;
using OpenNETCF.Windows.Forms.Calendar;
using Microsoft.WindowsMobile.PocketOutlook;

namespace OpenNETCF
{
    class POOMCalendarProvider: ICalendarDataProvider, IDisposable
    {
        OutlookSession session;
        public POOMCalendarProvider()
        {
            try
            {
                session = new OutlookSession();
                session.Appointments.Items.ListChanged += new System.ComponentModel.ListChangedEventHandler(Items_ListChanged);
            }
            catch
            {
                if (session != null)
                    session.Dispose();
                throw;
            }
        }

        void Items_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e)
        {
            if (ItemListChanged != null)
                ItemListChanged();
        }
        #region ICalendarDataProvider Members

        public CalendarItem[] GetItemsForDateRange(DateTime startDate, TimeSpan range)
        {
            AppointmentCollection appts = session.Appointments.Items.Restrict(string.Format("[Start] >= {0} AND [End] <= {1}", startDate.ToShortDateString(), startDate.Add(range).ToShortDateString()));
            List<CalendarItem> items = new List<CalendarItem>();
            foreach (Appointment appt in appts)
            {
                items.Add(new CalendarItem(appt.Start, appt.Duration, appt, appt.Subject));
            }
            return items.ToArray();
        }

        public event ItemListChangedDelegate ItemListChanged;

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            try
            {
                session.Dispose();
            }
            catch
            { }
        }

        #endregion
    }
}
